import json
import time
import unittest


import allure
import pytest
import requests
from pycparser.ply.cpp import tokens
from pycparser.ply.yacc import resultlimit
from  selenium import webdriver
from selenium.webdriver.common.by import By
from urllib3 import request

from Base.Base import Base
from Case import TestLogin
from Page.Login_Page import Login_Page
from Page.ShenHe_Page import ShenHe_Page
from Tools.Tools import log

#数据库配置


@pytest.fixture(scope="function")
def Case():
    with allure.step("启动浏览器"):
        driver=webdriver.Edge()
        driver.maximize_window()
    yield driver
    with allure.step("关闭浏览器"):
        time.sleep(3)
        driver.quit()
        print('测试结束')

@allure.feature('登录-审核列表')
class TestShen:
    @allure.title("管理员登录-审核列表中的一系列功能")
    @allure.severity(allure.severity_level.NORMAL)
    @allure.story("搜索功能")

    # @unittest.skip
    @pytest.mark.parametrize("shen_data",json.load(open("E:\GXPycharm\PythonObject\Help_PO_Ul\Data\Sou.json",encoding="utf-8")))
    def test_sou(self,Case,shen_data):
        name = shen_data['name']
        with allure.step("登录"):
            p=Login_Page(Case)
            p.test_login('admin','qwe123123')
        with allure.step('点击审核列表'):
            po=ShenHe_Page(Case)
            po.shenhe()
            allure.attach(Case.get_screenshot_as_png(),name='进入审核列表',
                          attachment_type=allure.attachment_type.PNG)
            log.info('进入审核列表')
            time.sleep(2)
        with allure.step('昵称框输入昵称'):
            po.name(name)
            time.sleep(2)
            allure.attach(Case.get_screenshot_as_png(),name='输入昵称后截图',
                          attachment_type=allure.attachment_type.PNG)
            log.info('输入昵称')

        with allure.step("点击搜索"):
            po.sou()
            allure.attach(Case.get_screenshot_as_png(),name='点击搜索后截图',
                          attachment_type=allure.attachment_type.PNG)
            log.info('点击搜索')


        #断言列表是否为空
        dy_list=Case.find_elements(By.XPATH,'/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr')
        log.info(len(dy_list))
        if name=='':
            assert len(dy_list)>0,"空搜索时，列表应为非空"
        else:
            #允许无效搜索词返回空列表，并验证是否显示“无结果”提示
            if len(dy_list)==0:
                no_list=Case.find_elements(By.XPATH,'/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/div/span')
                assert len(no_list) > 0 ,'列表为空但未显示无结果提示'
            else:
                assert len(dy_list)>0 ,f"搜索'{name}'后列表无结果"
            # 获取搜索结果列表
            log.info(f"前端搜索结果数量: {len(dy_list)}")

            # 数据库验证
            with allure.step('验证数据库'):
                sql = f"SELECT * FROM userinfo WHERE name = '{name}'"
                result = Base(Case).query_db(sql)
                log.info(f"数据库查询结果数量: {len(result) if result else 0}")

                if len(dy_list) > 0:  # 前端有结果
                    assert result, f"前端显示有'{name}'的结果，但数据库中没有找到"
                    log.info(f"数据库验证通过：找到{len(result)}条记录")
                else:  # 前端无结果
                    if not result:  # 数据库确实没有
                        log.info(f"数据库验证通过：'{name}'确实不存在")
                    else:  # 数据库有但前端没显示
                        assert False, f"数据库中有'{name}'记录({len(result)}条)，但前端未显示"
    @unittest.skip
    def test_bohui(self,Case):
        with allure.step('获取token'):
            response = requests.post(url='http://10.59.9.21/api/user/login',
                                     json={"username": "admin", "password": "8i4De25KlVQVwqTDgTNGqw=="})

            token = response.json()['token']
            # 调用接口同意接单员
            url = 'http://10.59.9.21/api/wx/user/info/pass'
            json = {
                "id": 102
            }
            headers = {'Token': token}
            requests.post(url=url, json=json, headers=headers)
            #数据库断言 是否 同意申请
            sql = f"SELECT state FROM userinfo WHERE id=102"
            result = Base(Case).query_db(sql)
            assert result[0]['state'] == 1, '同意失败'
            log.info(result)
            print(result)
        with allure.step('驳回'):
            p=ShenHe_Page(Case)
            p.test_bo()
            #数据库断言是否被驳回
            sql=f"SELECT state FROM userinfo WHERE id=102"
            result1=Base(Case).query_db(sql)
            assert  result1[0]['state']==2,'驳回失败'
            log.info(result1)
            print(result1)